package com.xiaoyu.client.ui.activity.help;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Build;
import android.support.annotation.NonNull;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.xiaoyu.client.ClientConstants;
import com.xiaoyu.client.R;
import com.xiaoyu.client.adapter.seek.SeekReplyOneRecyAdapter;
import com.xiaoyu.client.model.seek.SeekDetailBean;
import com.xiaoyu.client.model.seek.SeekParam;
import com.xiaoyu.client.model.seek.SeekReplyParam;
import com.xiaoyu.client.network.NetworkManager;
import com.xiaoyu.client.ui.activity.PhotoViewActivity;
import com.xiaoyu.client.ui.activity.forum.ForumDetailActivity;
import com.xiaoyu.client.ui.activity.forum.ForumFloatEditorActivity;
import com.xiaoyu.client.ui.activity.home.HomeSearchActivity;
import com.xiaoyu.client.ui.dialog.ShareDialog;
import com.xiaoyu.client.ui.fragment.help.MySeekFragment;
import com.xiaoyu.client.ui.fragment.help.SeekModel;
import com.xiaoyu.client.ui.fragment.main.HelpFragment;
import com.xiaoyu.client.ui.fragment.main.HomeFragment;
import com.xiaoyu.commonlib.network.CommonHttpResponser;
import com.xiaoyu.commonlib.ui.OnItemRecyClickListener;
import com.xiaoyu.commonlib.ui.base.BaseActivity;
import com.xiaoyu.commonlib.utils.CCircleImageView;
import com.xiaoyu.commonlib.utils.StatusBarUtil;
import com.xiaoyu.commonlib.utils.ToastUtil;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import static com.xiaoyu.commonlib.utils.CheckFormatUtils.isClientAvailable;

/**
 * 求助详情（求助回答）
 */
public class HelpDetailActivity extends AppCompatActivity implements View.OnClickListener, TextView.OnEditorActionListener {
    public static final String SEEK_ID = "seek_detail_seek_id";
    public static final String REPLY_ID = "seek_detail_reply_id";
    public static final String USER_ID = "seek_detail_user_id";
    public static final String POSITION = "position";
    public static final String PIC_ICON = "pic_icon";
    private ImageView backBtn;//返回
    private ImageView shareBtn;//分享
    private CCircleImageView helperPhoto;//求助者头像
    private TextView helperName;//求助者昵称
    private TextView helperPublishTime;//求助者发布时间
    private ImageView problemStatus;//问题解决状态
    private TextView problemContent;//问题内容
    private LinearLayout problemImgs;//问题图片描述
    private TextView collectBtn;//收藏按钮
    private TextView helpNum;//以帮助数目
    private TextView typeTxt;//问题分类
    private TextView locateTxt;//发布位置
    private TextView askCloselyTxt;//追问内容
    private TextView appendBtn;//追加问题按钮
    private TextView overBtn;//结束问题按钮
    private EditText replyEdit;//回复编辑框
    private SmartRefreshLayout mRefreshLayout;
    private RecyclerView replyLayout;
    private List<SeekReplyParam> mReplyList = new ArrayList<>();//回复数据
    private int page = 1;//页数
    private int count;//总页数
    private String seekId;//求助id
    private String userId;//求助用户id
    private SeekReplyOneRecyAdapter mAdapter;
    private boolean isCollect;//是否收藏
    private TextView mIssueTxt;//发布按钮

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_help_detail);
        if (getSupportActionBar() != null) {
            getSupportActionBar().hide();
        }
        StatusBarUtil.StatusBarLightMode(this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setStatusBarColor(getResources().getColor(R.color.colorWhite));
        }

        parseIntent();
        initView();
    }


    //接收上一页传过来的值
    private void parseIntent() {
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.getInt(ClientConstants.FROM) == ClientConstants.HELP_FRAGMENT) {
                seekId = bundle.getString(HelpFragment.SEEK_ID);
            }
            if (bundle.getInt(ClientConstants.FROM) == ClientConstants.MY_SEEK_FRAGMENT) {
                seekId = bundle.getString(SeekModel.SEEK_ID);
            }
            if(bundle.getInt(ClientConstants.FROM) == ClientConstants.FOR_YOU_MELANCHOLY){
                seekId = bundle.getString(HomeFragment.SEEK_ID);
            }
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        page = 1;
        getSeekDetail();
    }

    //初始化界面
    private void initView() {
        backBtn = findViewById(R.id.activity_help_detail_title_back_btn);
        shareBtn = findViewById(R.id.activity_help_detail_title_share_btn);
        helperPhoto = findViewById(R.id.activity_help_detail_problem_portrait);
        helperName = findViewById(R.id.activity_help_detail_problem_name_txt);
        helperPublishTime = findViewById(R.id.activity_help_detail_problem_publish_time_txt);
        problemStatus = findViewById(R.id.activity_help_detail_problem_solve_status_img);
        problemContent = findViewById(R.id.activity_help_detail_problem_content_txt);
        problemImgs = findViewById(R.id.activity_help_detail_problem_img_container);
        collectBtn = findViewById(R.id.activity_help_detail_problem_collect_btn);
        helpNum = findViewById(R.id.activity_help_detail_problem_solved_num_txt);
        typeTxt = findViewById(R.id.activity_help_detail_problem_type_label_txt);
        locateTxt = findViewById(R.id.activity_help_detail_problem_locate_txt);
        askCloselyTxt = findViewById(R.id.activity_help_detail_problem_ask_closely_content_txt);
        mRefreshLayout = findViewById(R.id.activity_help_detail_reply_refresh_layout);
        replyLayout = findViewById(R.id.activity_help_detail_reply_list_container);
        appendBtn = findViewById(R.id.activity_help_detail_problem_append_btn);
        overBtn = findViewById(R.id.activity_help_detail_problem_over_btn);
        replyEdit = findViewById(R.id.activity_help_detail_bottom_reply_edit);
        mIssueTxt = findViewById(R.id.activity_help_details_issue);

        replyEdit.setSingleLine(true);
        replyEdit.setImeOptions(EditorInfo.IME_ACTION_SEND);
        replyEdit.setInputType(EditorInfo.TYPE_CLASS_TEXT);

        replyEdit.setOnEditorActionListener(this);
        initRecy();

        mRefreshLayout.setEnableRefresh(false);
        mRefreshLayout.setNoMoreData(false);
        mRefreshLayout.setOnLoadMoreListener(onLoadMoreListener);

        backBtn.setOnClickListener(this);
        shareBtn.setOnClickListener(this);
        collectBtn.setOnClickListener(this);
        appendBtn.setOnClickListener(this);
        overBtn.setOnClickListener(this);
        helperPhoto.setOnClickListener(this);
        helperName.setOnClickListener(this);
        mIssueTxt.setOnClickListener(this);
    }

    private void initRecy() {
        LinearLayoutManager manager = new LinearLayoutManager(this);
        manager.setOrientation(LinearLayoutManager.VERTICAL);
        replyLayout.setLayoutManager(manager);
        mAdapter = new SeekReplyOneRecyAdapter(this, mReplyList);
        replyLayout.setAdapter(mAdapter);
        mAdapter.setOnItemRecyClickListener(itemReplyClickListener);

        replyLayout.setNestedScrollingEnabled(false);
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        if (v == backBtn) {//返回
            onBackPressed();
        } else if (v == shareBtn) {//分享
            if (!UMShareAPI.get(this).isInstall(this, SHARE_MEDIA.WEIXIN)) {
                ToastUtil.showBelowToast(this, "您还未安装微信");
                return;
            }
            toShare();

        } else if (v == collectBtn) {//收藏
            collectOrcancle();

        } else if (v == appendBtn) {//追加问题
            if (TextUtils.isEmpty(askCloselyTxt.getText().toString())) {
                intent = new Intent(this, SeekProblemAppendActivity.class);
                intent.putExtra(SEEK_ID, seekId);
                startActivity(intent);
            } else {
                ToastUtil.showToast(this, "只能追问一次哦");
            }
        } else if (v == overBtn) {//结束问题
            intent = new Intent(this, SeekOverActivity.class);
            intent.putExtra(SEEK_ID, seekId);
            startActivity(intent);
        } else if (v == helperPhoto) {//用户头像
            intent = new Intent(this, UserSeekInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_SEEK_DETAIL);
            bundle.putString(USER_ID, userId);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (v == helperName) {//用户昵称
            intent = new Intent(this, UserSeekInfoActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_SEEK_DETAIL);
            bundle.putString(USER_ID, userId);
            intent.putExtras(bundle);
            startActivity(intent);
        } else if (v == mIssueTxt) {
            //在这里做请求操作
            String inputContent = replyEdit.getText().toString();
            if (TextUtils.isEmpty(inputContent)) {
                ToastUtil.showToast(HelpDetailActivity.this, "请输入评论内容！");
            } else {
                //先隐藏键盘
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(getCurrentFocus()
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                toReply();
            }
        }
    }


    /**
     * 设置软键盘按钮监听
     */
    @Override
    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_SEND) {
            //在这里做请求操作
            String inputContent = replyEdit.getText().toString();
            if (TextUtils.isEmpty(inputContent)) {
                ToastUtil.showToast(HelpDetailActivity.this, "请输入评论内容！");
            } else {
                //先隐藏键盘
                ((InputMethodManager) getSystemService(INPUT_METHOD_SERVICE))
                        .hideSoftInputFromWindow(getCurrentFocus()
                                .getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                toReply();
            }
            return true;
        }
        return false;
    }


    /**
     * 一级回复中回复按钮点击监听
     */
    private OnItemRecyClickListener itemReplyClickListener = new OnItemRecyClickListener() {
        @Override
        public void onItemRecyClick(View view, int position) {
            Intent intent = new Intent(HelpDetailActivity.this, ForumFloatEditorActivity.class);
            Bundle bundle = new Bundle();
            bundle.putInt(ClientConstants.FROM, ClientConstants.FROM_SEEK_DETAIL);
            bundle.putString(SEEK_ID, seekId);
            bundle.putString(REPLY_ID, mReplyList.get(position).getSeekreplyid());
            intent.putExtras(bundle);
            startActivity(intent);
        }
    };

    //加载更多
    private OnLoadMoreListener onLoadMoreListener = new OnLoadMoreListener() {
        @Override
        public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
            if (page < count) {
                page = page + 1;
                getSeekDetail();
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(false);
            } else {
                mRefreshLayout.finishLoadMore();
                mRefreshLayout.setNoMoreData(true);
                mRefreshLayout.finishLoadMoreWithNoMoreData();
                Toast.makeText(HelpDetailActivity.this, "我是有底线的...", Toast.LENGTH_LONG).show();
            }
        }
    };

    /**
     * 获取求助详情
     */
    private void getSeekDetail() {
        NetworkManager.getSeekDetail(page, seekId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                parseSeekDetailSuc(result);
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {

            }
        });
    }

    private void parseSeekDetailSuc(String result) {
        if (page == 1) {
            mReplyList.clear();
            mAdapter.notifyDataSetChanged();
        }
        SeekDetailBean bean = new Gson().fromJson(result, SeekDetailBean.class);
        if (bean.getData().getReplay().size() != 0) {
            mReplyList.addAll(bean.getData().getReplay());
            mAdapter.notifyDataSetChanged();
        }
        userId = bean.getData().getSeekcontent().getUserid();
        count = Integer.parseInt(bean.getData().getCount());
        stuffData(bean.getData().getSeekcontent());

        String status = bean.getData().getStatus();
        if (status.equals("true")) {//是自己发的求助
            findViewById(R.id.activity_help_detail_bottom_layout_problem_btn_group).setVisibility(View.VISIBLE);
            findViewById(R.id.activity_help_detail_bottom_reply_layout).setVisibility(View.GONE);
        } else {//不是自己发的求助
            findViewById(R.id.activity_help_detail_bottom_layout_problem_btn_group).setVisibility(View.GONE);
            findViewById(R.id.activity_help_detail_bottom_reply_layout).setVisibility(View.VISIBLE);
        }
    }

    /**
     * 为控件绑定数据
     */
    private void stuffData(final SeekParam seekcontent) {
        helperName.setText(seekcontent.getNickname());
        Glide.with(this).load(seekcontent.getUserphoto()).into(helperPhoto);
        helperPublishTime.setText(seekcontent.getSeektime() + "发布");
        if (Integer.parseInt(seekcontent.getSeekstate()) == 0) {//未解决
            problemStatus.setImageResource(R.mipmap.icon_unsolved);
        } else {//已解决
            problemStatus.setImageResource(R.mipmap.icon_solved);
        }

        if (seekcontent.isCollect()) {//已收藏
            isCollect = true;
            collectBtn.setText("已收藏");
        } else {
            isCollect = false;
            collectBtn.setText("收藏问题");
        }
        problemContent.setText(seekcontent.getSeektitle());
        helpNum.setText("以帮助 " + seekcontent.getSeeksum());
        typeTxt.setText(seekcontent.getSeephelpname());
        locateTxt.setText(seekcontent.getSeekress());
        askCloselyTxt.setText(seekcontent.getSeekcontent());

        if (seekcontent.getSeekimg().size() > 0 && !seekcontent.getSeekimg().get(0).equals("")) {
            problemImgs.setVisibility(View.VISIBLE);
        }
        for (int i = 0; i < seekcontent.getSeekimg().size(); i++) {
            if (i < problemImgs.getChildCount()) {
                ImageView view = (ImageView) problemImgs.getChildAt(i);
                Glide.with(this).load(seekcontent.getSeekimg().get(i)).into(view);
                final int finalI = i;
                view.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(HelpDetailActivity.this, PhotoViewActivity.class);
                        intent.putExtra(ClientConstants.IMAGER_LIST_URL, (Serializable) seekcontent.getSeekimg());
                        intent.putExtra(ClientConstants.IMAGER_CLICK_POS, finalI);
                        startActivity(intent);
                    }
                });
            }
        }
    }


    /**
     * 收藏或取消收藏
     */
    private void collectOrcancle() {
        NetworkManager.collectOrCancleSeek(seekId, new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                if (isCollect) {
                    isCollect = false;
                    collectBtn.setText("收藏问题");
                } else {
                    isCollect = true;
                    collectBtn.setText("已收藏");
                }
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }


    /**
     * 求助回复
     */
    private void toReply() {
        NetworkManager.replySeek(seekId, "0", replyEdit.getText().toString(), new CommonHttpResponser() {
            @Override
            public void onSuccess(String result) {
                replyEdit.getText().clear();
                getSeekDetail();
            }

            @Override
            public void onFailed(String errorCode, String errorDiscription) {
            }
        });
    }


    /**
     * 发送分享
     */
    private void toShare() {
        UMImage image = new UMImage(this, R.drawable.share_logo);//网络图片
        image.compressStyle = UMImage.CompressStyle.SCALE;//大小压缩，默认为大小压缩，适合普通很大的图
        image.compressStyle = UMImage.CompressStyle.QUALITY;//质量压缩，适合长图的分享
        //压缩格式设置
        image.compressFormat = Bitmap.CompressFormat.PNG;//用户分享透明背景的图片可以设置这种方式，但是qq好友，微信朋友圈，不支持透明背景图片，会变成黑色

        UMWeb web = new UMWeb(ClientConstants.Share_Seek_Url + seekId);
        web.setTitle("你身边的卡车之家");//标题
        web.setThumb(image);  //缩略图
        web.setDescription("汽车、汽车配件、汽车用品的销售及网上销售，汽车配件的修理服务，车辆信息咨询服务，商务信息咨询服务，广告设计、制作、代理、发布。（依法须经批准的项目，经相关部门批");//描述

        new ShareAction(this).withMedia(web).
                setDisplayList(SHARE_MEDIA.WEIXIN, SHARE_MEDIA.WEIXIN_CIRCLE, SHARE_MEDIA.QQ, SHARE_MEDIA.SINA)
                .setCallback(shareListener).open();
    }

    /**
     * 友盟分享回调
     */
    private UMShareListener shareListener = new UMShareListener() {
        /**
         * @descrption 分享开始的回调
         * @param platform 平台类型
         */
        @Override
        public void onStart(SHARE_MEDIA platform) {

        }

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
//            ToastUtil.showBelowToast(HelpDetailActivity.this,"分享成功");
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Log.i("xiaoyuu", "分享失败  原因：" + t.toString());
            ToastUtil.showBelowToast(HelpDetailActivity.this, "分享失败");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showBelowToast(HelpDetailActivity.this, "取消了分享");
        }
    };

}
